﻿using AntC.AspNetCore.ApiEncryption.Internal;
using AntC.AspNetCore.ApiEncryption.Internal.Interfaces;
using Microsoft.Extensions.Options;
using System;
using System.Text;
using System.Threading.Tasks;

namespace AntC.AspNetCore.ApiEncryption.EncryptProviders
{
    /// <summary>
    /// Base64加密方式提供器
    /// </summary>
    public class Base64EncryptProvider : IEncryptProvider
    {
        /// <summary>
        /// 内容编码
        /// </summary>
        public Encoding ContentEncoding { get; set; }

        public Base64EncryptProvider(IOptionsSnapshot<EncryptProviderOptions> options)
        {
            ContentEncoding = Encoding.GetEncoding(string.IsNullOrWhiteSpace(options.Value.EncodingName) ? "utf-8" : options.Value.EncodingName);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="context"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<string> Decrypt(ApiEncryptionContext context, string content)
        {
            return ContentEncoding.GetString(Convert.FromBase64String(content));
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="context"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<string> Encrypt(ApiEncryptionContext context, string content)
        {
            context.HttpContext.Response.ContentType = $"text/plain; charset={ContentEncoding.HeaderName}";
            return Convert.ToBase64String(ContentEncoding.GetBytes(content));
        }
    }
}
